package com.wus.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wus.common.core.exception.BusinessException;
import com.wus.system.entity.SysDictData;
import com.wus.system.entity.SysDictType;
import com.wus.system.mapper.SysDictDataMapper;
import com.wus.system.mapper.SysDictTypeMapper;
import com.wus.system.request.SysDictDataDetailEditReq;
import com.wus.system.request.SysDictDataEditReq;
import com.wus.system.response.SysDictDataResp;
import com.wus.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author wus
 * @since 2025-01-06
 */
@RequiredArgsConstructor
@Service
public class SysDictDataServiceImpl implements ISysDictDataService {

    private final Logger logger = LoggerFactory.getLogger(SysDictDataServiceImpl.class);

    private final SysDictDataMapper baseMapper;

    private final SysDictTypeMapper dictTypeMapper;


    @Override
    public List<SysDictDataResp> getByDictType(String dictType) {
        List<SysDictData> sysDictDataList = this.getListByDictType(dictType);
        return sysDictDataList.stream().map(sysDictData -> {
            SysDictDataResp resp = new SysDictDataResp();
            BeanUtils.copyProperties(sysDictData, resp);
            return resp;
        }).toList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean edit(SysDictDataEditReq req) {
        SysDictType dictType = dictTypeMapper.selectById(req.getDictTypeId());
        if (dictType == null) {
            throw BusinessException.newInstance("字典类型不存在");
        }
        List<SysDictData> originalDictDataList = this.getListByDictType(dictType.getDictType());
        // 新增 or 编辑 or 移除
        List<SysDictData> addList = new ArrayList<>();
        List<SysDictData> updateList = new ArrayList<>();
        List<Long> updateIdList = new ArrayList<>();
        for (SysDictDataDetailEditReq detail : req.getDetailList()) {
            SysDictData sysDictData = new SysDictData();
            BeanUtils.copyProperties(detail, sysDictData);
            sysDictData.setDictType(dictType.getDictType());
            if (detail.getId() == null) {
                addList.add(sysDictData);
            } else {
                updateList.add(sysDictData);
                updateIdList.add(sysDictData.getId());
            }
        }
        // 删除被移除的部分记录，即补集
        if (!originalDictDataList.isEmpty()) {
            List<Long> originalAllIdList = originalDictDataList.stream().map(SysDictData::getId).toList();
            if (!updateIdList.isEmpty()) {
                // 取补集
                List<Long> removeList =  CollectionUtil.subtractToList(originalAllIdList, updateIdList);
                logger.info("删除被移除的记录：{}", removeList);
                if (!removeList.isEmpty()) {
                    baseMapper.deleteBatchIds(removeList);
                }
            }
        }
        updateList.forEach(sysDictData -> {
            baseMapper.update(sysDictData, Wrappers.<SysDictData>lambdaUpdate().eq(SysDictData::getId, sysDictData.getId()));
        });
        addList.forEach(baseMapper::insert);
        return Boolean.TRUE;
    }

    private List<SysDictData> getListByDictType(String dictType) {
        return baseMapper.selectList(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictType, dictType).orderByAsc(SysDictData::getDictSort));
    }
}
